//
//  CommentViewController.m
//  项目三
//
//  Created by rimi1 on 2016/12/12.
//  Copyright © 2016年 Wangxingqian. All rights reserved.
//

#import "CommentViewController.h"
#import "OtherPersonalViewController.h"
#import "SignInViewController.h"

#import "CommentView.h"
#import "CommentFootView.h"
#import "Alert.h"
#import "CommentNavigationBar.h"
#import "CommentTableViewCell.h"
#import "NotView.h"

#import "AVRequest+Comment.h"
#import "AVRequest+Relation.h"

@interface CommentViewController () <UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate>

@property (nonatomic, strong) CommentNavigationBar *nBar;
@property (nonatomic, strong) CommentView *commentView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray <AVObject *> *commentArr;
@property (nonatomic, strong) CommentFootView *footView;
@property (nonatomic, strong) NotView *notView;
@property (nonatomic, strong) UILabel *notCommentList;

@property (nonatomic, assign) CGFloat scrollY;

@end

@implementation CommentViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewWillAppear:(BOOL)animated {
    if ([MyUser sharedUser].isSignIn) {
        [self urlIsCollectRequest];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeDataSource];
    [self initializeAppearance];
}

#pragma mark - initialize

- (void)initializeDataSource {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShowNotification:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHideNotification:) name:UIKeyboardWillHideNotification object:nil];
    self.scrollY = 0;
    [self urlCommentListRequest];
}

- (void)initializeAppearance {
    self.view.backgroundColor = [UIColor whiteColor];
    [self initHead];
    self.tableView.tableHeaderView = self.commentView;
    [self.view addSubview:self.tableView];
    [self initBar];
    [self.view addSubview:self.footView];
    [self.view addSubview:self.inputView];
}

- (void)initBar {
    [self.navigationBar removeFromSuperview];
    self.nBar.backgroundColor = self.navigationBar.backgroundColor;
    [self.view addSubview:self.nBar];
    
    NSURL *url = [NSURL URLWithString:self.obj[@"user"][@"headImage"]];
    [self.nBar.headImage sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"个人"] options:SDWebImageProgressiveDownload];
    self.nBar.name.text = self.obj[@"user"][@"name"];
    self.nBar.works.text = [NSString stringWithFormat:@"%@个作品", self.obj[@"user"][@"myDynamicCount"]];
}

- (void)initHead {
    NSURL *url = [NSURL URLWithString:self.obj[@"img"]];
    [self.commentView.img sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"默认加载图"] options:SDWebImageProgressiveDownload completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        CGSize size = image.size;
        CGFloat ratio = size.width/kWIDTH;
        CGFloat height = size.height/ratio;
        
        self.commentView.name.text = self.obj[@"name"];
        self.commentView.food.text = [NSString stringWithFormat:@"%@", self.obj[@"food"]];
        [self.commentView initHeightWithImgHeight:height step:self.obj[@"step"]];
    }];
}

#pragma mark - URLRequest
// 评论列表
- (void)urlCommentListRequest {
    self.commentArr = [NSMutableArray array];
    [AVRequest avCommentWithObj:self.obj queryArr:^(NSArray *objects, NSError *error) {
        if (error) {
            [[RequestError sharedError] showErrorWithTitle:@"请求出错"];
            [self.view addSubview:self.notView];
            return;
        }
        [self.notView removeFromSuperview];
        
        if (objects.count == 0) {
            self.tableView.tableFooterView = self.notCommentList;
            return;
        }
        
        self.tableView.tableFooterView = [UIView new];
        for (NSInteger i = objects.count - 1; i >= 0; i--) {
            [self.commentArr addObject:objects[i]];
        }
        [self.tableView reloadData];
    }];
}
// 添加评论
- (void)urlAddCommentRequest {
    [AVRequest avAddCommentWithObj:self.obj content:self.footView.textField.text aSucceed:^(BOOL succeed, NSError *error) {
        if (error) {
            [Alert alertWithTitle:@"评论失败" message:nil];
            return;
        }
        
        if (succeed) {
            [Alert alertWithTitle:@"评论成功" message:nil];
            self.footView.textField.text = @"";
            [self urlCommentListRequest];
        }else {
            [Alert alertWithTitle:@"评论失败" message:nil];
        }
    }];
}
// 判断是否收藏
- (void)urlIsCollectRequest {
    [AVRequest avIsPersonalCollectWithObj:self.obj objArr:^(NSArray *objects, NSError *error) {
        if (error) {
            return;
        }
        
        if (objects.count == 0) {
            self.footView.collect.selected = NO;
        }else {
            self.footView.collect.selected = YES;
        }
    }];
}
// 删除收藏
- (void)urlRemoveRequest {
    [AVRequest avRemoveCollectWithObj:self.obj removeSucceed:^(BOOL succeed, NSError *error) {
        if (error) {
            [Alert alertWithTitle:@"取消收藏失败" message:nil];
            return;
        }
        
        if (succeed) {
            self.footView.collect.selected = NO;
            [Alert alertWithTitle:@"取消收藏成功" message:nil];
        }else {
            [Alert alertWithTitle:@"取消收藏失败" message:nil];
        }
    }];
}
// 添加收藏
- (void)urlAddRequest {
    [AVRequest avAddCollectWithDynamicObj:self.obj menuId:nil name:self.obj[@"name"] food:self.obj[@"food"] img:self.obj[@"img"] addSucceed:^(BOOL succeed, NSError *error) {
        if (error) {
            [Alert alertWithTitle:@"收藏失败" message:nil];
            return;
        }
        
        if (succeed) {
            self.footView.collect.selected = YES;
            [Alert alertWithTitle:@"收藏成功" message:nil];
        }else {
            [Alert alertWithTitle:@"收藏失败" message:nil];
        }
        
    }];
}

#pragma mark - KeyboardAnimation

- (void)keyboardWillShowNotification:(NSNotification *)notification {
    CGSize size = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    
    self.footView.transform = CGAffineTransformMakeTranslation(0, -size.height);
    CGRect rect = self.tableView.frame;
    rect.size.height = kHEIGHT - size.height - 64;
    self.tableView.frame = rect;
}

- (void)keyboardWillHideNotification:(NSNotification *)notification {
    CGSize size = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    
    self.footView.transform = CGAffineTransformMakeTranslation(0, 0);
    CGRect rect = self.tableView.frame;
    rect.size.height += size.height;
    self.tableView.frame = rect;
}

#pragma mark - respondsTo...
// 100 = back  101 = 收藏  102 = 发送评论
- (void)respondsToFoot:(UIButton *)sender {
    switch (sender.tag) {
        case 100:{
            [self.navigationController popViewControllerAnimated:YES];
        }
            break;
            
        case 101:{
            if ([MyUser sharedUser].isSignIn) {
                if (self.footView.collect.selected) {
                    [self urlRemoveRequest];
                }else {
                    [self urlAddRequest];
                }
            }else {
                [self.view endEditing:YES];
                SignInViewController *signIn = [[SignInViewController alloc] init];
                [self.navigationController pushViewController:signIn animated:YES];
            }
            
        }
            break;
            
        case 102:{
            if ([MyUser sharedUser].isSignIn) {
                if (self.footView.textField.text.length != 0) {
                    [self urlAddCommentRequest];
                }
            }else {
                [self.view endEditing:YES];
                SignInViewController *signIn = [[SignInViewController alloc] init];
                [self.navigationController pushViewController:signIn animated:YES];
            }
            
        }
            break;
            
        default:
            break;
    }
}

- (void)respondsToHead {
    OtherPersonalViewController *personal = [[OtherPersonalViewController alloc] init];
    personal.obj = self.obj[@"user"];
    [self.navigationController pushViewController:personal animated:YES];
}

- (void)respondsToCellHead:(CommentTableViewCell *)cell {
    NSInteger row = [self.tableView indexPathForCell:cell].row;
    AVObject *obj = self.commentArr[row];
    OtherPersonalViewController *personal = [[OtherPersonalViewController alloc] init];
    personal.obj = obj[@"user"];
    [self.navigationController pushViewController:personal animated:YES];
}

- (void)respondsToKeyBoder {
    [self.view endEditing:YES];
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat y = scrollView.contentOffset.y;
    if (y <= -20) {
        [self navigationBarAnimationWithIs:YES];
        return;
    }
    
    if (self.scrollY < y) {
        // 导航栏消失
        [self navigationBarAnimationWithIs:NO];
    }else {
        // 导航栏出现
        [self navigationBarAnimationWithIs:YES];
    }
    
    self.scrollY = y;
}

- (void)navigationBarAnimationWithIs:(BOOL)is {
    CGFloat lucent;
    if (is) {
        lucent = 1;
    }else {
        lucent = 0;
    }
    [UIView animateWithDuration:0.25 animations:^{
        self.nBar.alpha = lucent;
    }];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.commentArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reusing = @"CommentCell";
    CommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reusing];
    if (!cell) {
        cell = [[CommentTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reusing];
    }
    AVObject *obj = self.commentArr[indexPath.row];
    
    cell.obj = obj;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    __weak CommentViewController *comment = self;
    cell.tapHead = ^(CommentTableViewCell *cell) {
        [comment respondsToCellHead:cell];
    };
    
    return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    AVObject *obj = self.commentArr[indexPath.row];
    return [CommentTableViewCell cellHeightWithText:obj[@"content"]];
}

#pragma mark - get

- (CommentNavigationBar *)nBar {
    
    if (!_nBar) {
        
        _nBar = [[CommentNavigationBar alloc] initWithFrame:CGRectMake(0, 0, kWIDTH, 64)];
        
        __weak CommentViewController *comment = self;
        _nBar.tapHead = ^() {
            [comment respondsToHead];
        };
        
    }
    return _nBar;
}

- (CommentView *)commentView {
    
    if (!_commentView) {
        
        _commentView = [[CommentView alloc] initWithFrame:CGRectMake(0, 0, kWIDTH, 500)];
        
    }
    return _commentView;
}

- (UITableView *)tableView {
    
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kWIDTH, kHEIGHT - 49) style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableFooterView = [UIView new];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(respondsToKeyBoder)];
        [_tableView addGestureRecognizer:tap];
        
    }
    return _tableView;
}

- (CommentFootView *)footView {
    
    if (!_footView) {
        
        _footView = [[CommentFootView alloc] initWithFrame:CGRectMake(0, kHEIGHT - 49, kWIDTH, 49)];
        _footView.layer.shadowOffset = CGSizeMake(0, -5);
        _footView.layer.shadowOpacity = 0.3;
        __weak CommentViewController *comment = self;
        _footView.buttonBlock = ^(UIButton *sender) {
            [comment respondsToFoot:sender];
        };
        _footView.backgroundColor = [UIColor whiteColor];
        
    }
    return _footView;
}

- (NotView *)notView {
    
    if (!_notView) {
        
        _notView = [[NotView alloc] initWithFrame:CGRectMake(0, 64, kWIDTH, kHEIGHT - 64 - 49)];
        _notView.backgroundColor = [UIColor whiteColor];
        _notView.title.text = @"请求错误";
        
        __weak CommentViewController *fc = self;
        _notView.tapRefresh = ^() {
            [fc urlCommentListRequest];
            if ([MyUser sharedUser].isSignIn) {
                [fc urlIsCollectRequest];
            }
        };
        
    }
    return _notView;
}

- (UILabel *)notCommentList {
    
    if (!_notCommentList) {
        
        _notCommentList = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kWIDTH, 60)];
        _notCommentList.textAlignment = NSTextAlignmentCenter;
        _notCommentList.font = [UIFont systemFontOfSize:WXQAdaptionHeight(15)];
        _notCommentList.text = @"还没有任何评论，快来抢个沙发吧";
        
    }
    return _notCommentList;
}

@end















